import type { AxiosResponse, CreateAxiosDefaults } from 'axios'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { HttpCode } from '../enums'

const {
  VITE_PROTOCOL,
  VITE_BASE_URL,
} = import.meta.env

type IOptions = CreateAxiosDefaults & {
  responseOriginData?: boolean
}

function handleHttpError(code: number) {
  const message = {
    [HttpCode.HTTP_400]: '请求错误',
    [HttpCode.HTTP_401]: '未授权',
    [HttpCode.HTTP_403]: '没有访问权限',
    [HttpCode.HTTP_404]: '资源不存在 ',
    [HttpCode.HTTP_405]: '目标资源不支持该请求方法',
    [HttpCode.HTTP_500]: '服务器错误',
    [HttpCode.HTTP_502]: '网关错误',
    [HttpCode.HTTP_503]: '服务器没有准备好处理请求，常见原因是服务器因维护或重载而停机',
    [HttpCode.HTTP_504]: '网关超时',
  }[code]
  ElMessage.error(message || '服务器出小差啦！')
}

class AxiosInstanceWrapper {
  private instance

  constructor(option?: IOptions) {
    this.instance = axios.create({
      baseURL: VITE_PROTOCOL + VITE_BASE_URL,
      timeout: 1000 * 60,
      ...(option || {}),
    })

    this.instance.interceptors.request.use((config) => {
      return config
    })

    this.instance.interceptors.response.use((res: AxiosResponse) => {
      if (res.status >= 400) {
        handleHttpError(res.status)
        return
      }

      // if (res.status !== 200) {
      //   ElMessage({
      //     type: 'error',
      //     message: '接口异常',
      //     duration: 3000,
      //   })
      //   Promise.reject(new Error('接口异常'))
      //   return
      // }

      // if (!option?.responseOriginData && res.data?.http_status !== 200) {
      //   ElMessage({
      //     type: 'error',
      //     message: res.data?.msg || '接口异常',
      //     duration: 3000,
      //   })
      //   Promise.reject(new Error(res.data?.msg || '接口异常'))
      //   return
      // }

      return option?.responseOriginData ? res : res.data.result
    }, (e) => {
      // handleHttpError(e)
      return Promise.reject(e)
    })
  }

  getInstance() {
    return this.instance
  }
}

export function getHttp(option?: IOptions) {
  const instance = new AxiosInstanceWrapper(option || {}).getInstance()

  instance.defaults.headers.post['Content-Type'] = 'application/json'

  return instance
}
